from app import db
from blueprints import api_blueprint
from blueprints.personal.api.identity import PersonalIdentity
from blueprints.personal.api.information import PersonalInformation
from tools.model import QueryOneInstance, UpdateInstance
from tools.response import Response, ResponsePostJson
from flask import redirect, url_for, session
from werkzeug.security import generate_password_hash, check_password_hash

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(300), nullable=False, unique=True)
    password = db.Column(db.String(300), nullable=False)

def NewUser(data):
    user = User()
    UpdateInstance(user,data)
    UpdateInstance(PersonalInformation(),{"uid":user.id})
    UpdateInstance(PersonalIdentity(),{"uid":user.id})

@api_blueprint.route('/register', methods=['POST'])
def register():
    def cb(json):
        user = QueryOneInstance(User, {'username': json['username']})
        if not user:
            json['password'] = generate_password_hash(json['password'])
            NewUser(json)
            return Response("注册成功")
        return Response("已存在用户")

    return ResponsePostJson(['username', 'password'], cb)

@api_blueprint.route('/login', methods=['POST'])
def login():
    def cb(json):
        user = User.query.filter_by(username=json['username']).first()
        if user is None:
            return Response('用户不存在')
        if check_password_hash(user.password, json['password']):
            session['uid'] = user.id
            session['username'] = user.username
            # TODO url
            return redirect(url_for('personal.information'))
        return Response('用户名与密码不匹配')

    return ResponsePostJson(['username', 'password'], cb)




